import os
import json
import shutil
from sympy import arg
import win32api
import win32print
import random
import string
from copy import deepcopy
import re
import time
import datetime
import tkinter as tk
import tkinter.messagebox
from docx import Document
import requests
from multiprocessing.dummy import Pool
from lxml import etree
import pyperclip
import windnd
import utils
import hyd_manully
import openpyxl
import comunacation
import cn_consult
r"""
pyinstaller -D -w -i .\1.ico shift_rec.py

"""


# 自定义无信息异常
class NoInfoError(Exception):
    pass


def print_file(filename):
    win32api.ShellExecute(0, 'print', filename,
                          '/d:"%s"' % win32print.GetDefaultPrinter(), '.', 0)


class MySession(requests.Session):
    def request(self, *args, **kwargs):
        kwargs.setdefault('timeout', 5)
        return super(MySession, self).request(*args, **kwargs)

class AcquireInfoTotal(object):
    def __init__(self, pid):
        self.pid = pid
        get_params = {'id': str(pid)}

        self.headers = {
            "User-Agent":
            "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"
        }

        url_get = "http://10.68.1.38:8000/doqleiview/doqleiview.aspx"

        # self.users = requests.Session()
        self.users = MySession()

        get_basic_content = self.users.get(url_get,
                                           params=get_params,
                                           headers=self.headers)

        self.basic_html_doc = get_basic_content.text
        basic_tree = etree.HTML(self.basic_html_doc)

        self.basic_param_patient = basic_tree.xpath(
            '//ul[@class="ztree"]')[0].attrib
        basic_param_code = basic_tree.xpath(
            '//div[contains(@class, "model_menu_items")]')[0].attrib
        post_param_menu = {
            'type': self.basic_param_patient['data-type'],
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'idata[0].key': 'uhid',
            'idata[0].value': basic_param_code["data-uhid"],
            'idata[1].key': 'date_validated',
            'idata[1].value': self.basic_param_patient['data-date_validated'],
            'idata[2].key': 'treatment',
            'idata[2].value': basic_param_code["data-uhid"].split(']')[1],
        }
        url_menu = "http://10.68.1.38:8000/Menu/MedicalMenu"

        self.menu_json_data = self.users.post(url_menu,
                                              headers=self.headers,
                                              data=post_param_menu)

    def query_content(self, query_kind='病程记录'):
        
        menu_respond = self.menu_json_data.json()
        test_info_data = {}
        for i in menu_respond['Data']:

            test_info_data.update(i.setdefault('Data', {}))

            if i.setdefault('Text', '') == query_kind:
                mtype = i['Type']
                break
            if i.setdefault('Children', ''):
                for j in i['Children']:
                    test_info_data.update(j.setdefault('Data', {}))
                    if j.setdefault('Text', '') == query_kind:
                        mtype = j['Type']

                        break
                else:
                    continue
                break

        post_para_test = {
            'type': self.basic_param_patient['data-type'],
            'patientid': '☆',
            'snick': '',
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'patientname': self.basic_param_patient['data-patientname'],
            'official1': self.basic_param_patient['data-official1'],
            'mtype': mtype,
        }

        index_ = 0
        for k, v in test_info_data.items():
            post_para_test['idata[%s].key' % index_] = k
            post_para_test['idata[%s].value' % index_] = v
            index_ += 1

        url_result = "http://10.68.1.38:8000/Content/Index"
       
        try:
            
            result = self.users.post(
                url_result,
                headers=self.headers,
                data=post_para_test,
                timeout=3,
            ).text
           
        except requests.exceptions.ReadTimeout as e:
        
           
            result = ''
        # with open(f'{query_kind}.txt', 'w+', encoding='utf-8') as f:
        #     f.write(result)
        return {query_kind: result}


class DataResolver(object):
    def __init__(self, pid):
        self.patient_info = {}
        self.pid = pid
        self.result_dic = ''

    @staticmethod
    def do_table(html_grab):
        tree = etree.HTML(html_grab)
        tables = tree.xpath('//table')
        result_list = []
        for table in tables:
            table_dic = {}
            trs = table.findall('.//tr')
            table_dic['test_title'] = trs[0].find('.//td//input').attrib.get(
                'value').split('(')[0]
            test_date = trs[0].find('.//td//input').attrib.get('value').split(
                '(')[1]
            test_date = test_date.strip()
            test_date = test_date.strip(':')
            test_date = test_date.strip(')')
            table_dic['test_date'] = test_date
            table_dic['test_result'] = []
            for tr in trs[2:]:
                tds = tr.findall('.//td')
                result_details = {
                    'title':
                    tds[1].text,
                    'result':
                    tds[2].text.strip(),
                    'note':
                    tds[3].find('./font').text,
                    'flag':
                    '升高' if tds[3].find('./font').text == '↑' else
                    ('降低' if tds[3].find('./font').text == '↓' else '正常')
                }

                table_dic['test_result'].append(result_details)
            result_list.append(table_dic)
        return result_list

    @staticmethod
    def do_test(test_result):
        result_dic = {}
        with open('.\\myjson\\spliter.json', 'r', encoding='utf-8') as load_f:
            load_dic = json.load(load_f)

        for each_test_dic in test_result:

            for k_test in load_dic.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[
                                k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key in load_dic[k_test].keys():
                            if each_test_key in each_test_result["title"]:
                                if each_test_result["flag"] in load_dic[
                                        k_test][each_test_key].keys():
                                    result_dic[k_test][
                                        each_test_dic["test_date"]].append({
                                            "项目":
                                            each_test_result["title"],
                                            "结果":
                                            "%s %s" %
                                            (each_test_result["result"],
                                             load_dic[k_test][each_test_key]
                                             ["单位"]),
                                            "提示":
                                            load_dic[k_test][each_test_key][
                                                each_test_result["flag"]]
                                        })

        with open('.\\myjson\\test_analysis.json', 'r', encoding='utf-8') as load_f:
            test_load = json.load(load_f)
        for each_test_dic in test_result:

            for k_test in test_load.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[
                                k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key_analysis in test_load[k_test].keys():
                            if each_test_key_analysis in each_test_result[
                                    "title"]:

                                if each_test_result["result"] != test_load[
                                        k_test][each_test_key_analysis]:
                                    result_dic[k_test][
                                        each_test_dic["test_date"]].append({
                                            "项目":
                                            each_test_result["title"],
                                            "结果":
                                            each_test_result["result"],
                                            "提示":
                                            ""
                                        })

        result_string = '入院根据当前疫情防控及上级文件要求：查新型冠状病毒核酸检测示阴性。'
        for each_test_kind, each_test_kind_v in result_dic.items():
            if each_test_kind:
                result_string += '%s：' % each_test_kind

            for index_v, data_v in enumerate(each_test_kind_v.values()):
                if data_v:
                    if index_v > 0 and each_test_kind:
                        result_string += '%s：' % each_test_kind
                    normal = True

                    for each_data_dict in data_v:

                        result_string += '%s：%s ' % (each_data_dict['项目'],
                                                     each_data_dict['结果'])
                        if each_data_dict['提示']:
                            normal = False
                            result_string += '%s' % each_data_dict['提示']
                    if normal and each_test_kind in load_dic.keys():
                        result_string += '未见明显异常。'
                elif not data_v and each_test_kind:
                    result_string += "未见异常。"

        return result_string

    def record_resolve(self, html_dic):
        tree = etree.HTML(html_dic['病程记录'])
        basic_info_td = tree.xpath('//div[@esttype="入院记录"]//table')[0].xpath(
            './/td//text()') if tree.xpath(
                '//div[@esttype="入院记录"]//table') else []
        for i in basic_info_td:
            i = i.strip()
            if i:
                info_list = i.split("：")
                try:
                    self.patient_info[info_list[0]] = info_list[1]
                except IndexError as e:
                    info_list = i.split(":")
                    self.patient_info[info_list[0]] = info_list[1]

        self.patient_info["住院号"] = str(self.pid)
        self.patient_info["入院日期"] = self.patient_info.setdefault(
            '入院时间', '无信息').split()[0]
        self.patient_info["主诉"] = tree.xpath(
            '//div[@esttype="入院记录"]//span[@itemid="5"]')[0].text if tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="5"]') else '无信息'

        self.patient_info["医师"] = tree.xpath(
            '//div[@esttype="入院记录"]//span[@itemid="2"]')[0].text.split(
                "：")[1] if tree.xpath(
                    '//div[@esttype="入院记录"]//span[@itemid="2"]') else '无信息'
        self.patient_info["诊断"] = " ".join(
            tree.xpath('//div[@esttype="入院记录"]//span[@itemid="8"]'
                       )[0].xpath('string(.)').split()[1:] if tree.
            xpath('//div[@esttype="入院记录"]//span[@itemid="8"]') else '无信息')
        self.patient_info["现病史"] = tree.xpath(
            '//div[@esttype="入院记录"]//span[@itemid="6"]')[0].text if tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="6"]') else "无信息"
        self.patient_info["TPRBP"] = tree.xpath(
            '//div[@esttype="入院记录"]//span[@itemid="10"]')[0].xpath(
                'string(.)') if tree.xpath(
                    '//div[@esttype="入院记录"]//span[@itemid="10"]') else "无信息"
        # print(self.patient_info["TPRBP"])
        self.patient_info["入院体检"] = tree.xpath(
            '//div[@esttype="入院记录"]//p[@class="childmouseover"]'
        )[0].xpath('string(.)').strip() if tree.xpath(
            '//div[@esttype="入院记录"]//p[@class="childmouseover"]') else "无信息"
        self.patient_info["入院化验单"] = \
            tree.xpath('//div[@esttype="入院记录"]//p[@class="childmouseover"]/following-sibling::p/following-sibling::p//text()')[0] if tree.xpath('//p[@class="childmouseover"]/following-sibling::p/following-sibling::p//text()') else "无信息"
        self.patient_info["病人简介"] = tree.xpath(
            '//div[@esttype="首次病程记录"]//span[@itemid="1"]'
        )[0].text if tree.xpath(
            '//div[@esttype="首次病程记录"]//span[@itemid="1"]') else "无信息"
        self.patient_info[
            "入院情况(出院记录)"] = f"{self.patient_info['病人简介']} 以“{self.patient_info['主诉']}”入院。体格检查：{self.patient_info['TPRBP']}，{self.patient_info['入院体检']}"
        first_info_p = tree.xpath('//div[@esttype="首次病程记录"]//p')[1].xpath(
            'string(.)').strip() if tree.xpath(
                '//div[@esttype="首次病程记录"]//p') else '无信息'

        content_1 = re.findall(
            r".+病例特点(.*?)1(\.|、)(.+?)2(\.|、)(.*?)(查体|体格检查).+?", first_info_p,
            re.DOTALL)
        if content_1:
            self.patient_info['病例特点'] = content_1[0][2]
        content_2 = re.findall(
            r".+诊疗计划(.*?)1(\.|、)(.+?)2(\.|、)(.+?)3(\.|、)(.+?)4(\.|、)(.+)\d?",
            first_info_p, re.DOTALL)

        if content_2:
            
            self.patient_info['诊疗计划'] = content_2[0][2::2]
        # LIS报告单
        lis_data = html_dic.setdefault('LIS报告单', '')
        if lis_data:
            result_lis = self.do_table(lis_data)

            result_lis = self.do_test(result_lis)

            self.patient_info['化验单'] = result_lis
        else:
            self.patient_info['化验单'] = '入院根据当前疫情防控及上级文件要求：查新型冠状病毒核酸检测示阴性。'
        # PACS报告单
        pacs_data = html_dic.setdefault('PACS报告单', '')
        if pacs_data:
            result_pacs = self.do_pacs(pacs_data)
            self.patient_info['影像学'] = result_pacs
        self.patient_info['出院日期'] = tree.xpath(
            '//div[@esttype="出院记录"]//table')[0].xpath('.//td')[5].xpath(
                'string(.)').strip().split('：')[1].split()[0] if tree.xpath(
                    '//div[@esttype="出院记录"]//table') else '无信息'
        self.patient_info['出院时间'] = tree.xpath(
            '//div[@esttype="出院记录"]//table')[0].xpath('.//td')[5].xpath(
                'string(.)').strip().split('：')[1] if tree.xpath(
                    '//div[@esttype="出院记录"]//table') else '无信息'
        self.patient_info["出院诊断"] = tree.xpath(
            '//div[@esttype="出院记录"]//span[@itemid="1"]')[0].xpath(
                'string(.)') if tree.xpath(
                    '//div[@esttype="出院记录"]//span[@itemid="1"]') else '无信息'
        self.patient_info["诊疗经过"] = tree.xpath(
            '//div[@esttype="出院记录"]//p')[4].xpath('string(.)').split(
                '：')[1] if tree.xpath('//div[@esttype="出院记录"]//p') else '无信息'
        self.patient_info["出院情况"] = tree.xpath(
            '//div[@esttype="出院记录"]//p')[6].xpath('string(.)').split(
                '：')[1] if tree.xpath('//div[@esttype="出院记录"]//p') else '无信息'

        self.patient_info["出院医嘱"] = tree.xpath(
            '//div[@esttype="出院记录"]//p')[7].xpath('string(.)').split(
                '：')[1] if tree.xpath('//div[@esttype="出院记录"]//p') else '无信息'

        self.patient_info["病史"] = '%s 患儿以“%s”为代主诉入院 查体：%s %s 初步诊断：%s 治疗：%s' % (
            self.patient_info.setdefault('入院时间', '').split()[1]
            if self.patient_info.setdefault('入院时间', '') else '无信息',
            self.patient_info.setdefault('主诉', '无信息'),
            self.patient_info.setdefault('TPRBP', '无信息'),
            self.patient_info.setdefault('入院体检', '无信息'),
            self.patient_info.setdefault('诊断', '无信息'),
            self.patient_info.setdefault('诊疗计划', '')[1]
            if self.patient_info.setdefault('诊疗计划', '') else '无信息',
        )
        return self.patient_info

    def check_keywords(self, html_dic, key_words):
        result = {}
        tree = etree.HTML(html_dic['病程记录'])
        for key_word in key_words:
            result[key_word] = {'results': []}
            for each in tree.xpath(f'//div[contains(@esttype, "{key_word}")]'):
                if each:
                    
                    date_result = ' '.join(
                        each.xpath('p')[0].xpath('string(.)').split('\n')
                        [0].split()[:2])
                    name_result = each.xpath('p')[0].xpath('string(.)').split(
                        '\n')[0].split()[2]
                    record_result = each.xpath('p')[1].xpath('string(.)')
                    result[key_word]['results'].append({
                        'date_result':
                        date_result,
                        'name_result':
                        name_result,
                        'record_result':
                        record_result
                    })
                    basic_info_td = tree.xpath(
                        '//div[@esttype="入院记录"]//table')[0].xpath(
                            './/td//text()') if tree.xpath(
                                '//div[@esttype="入院记录"]//table') else []

                    basic_info = {}
                    for i in basic_info_td:
                        i = i.strip()
                        if i:
                            info_list = i.split("：")
                            basic_info[info_list[0]] = info_list[1]
                    result[key_word]['姓名'] = basic_info['姓名']
                    result[key_word]['性别'] = basic_info['性别']
                    result[key_word]['年龄'] = basic_info['年龄']
                    result[key_word]["住院号"] = str(self.pid)
                    result[key_word]["出院诊断"] = tree.xpath(
                        '//div[@esttype="出院记录"]//span[@itemid="1"]'
                    )[0].xpath('string(.)') if tree.xpath(
                        '//div[@esttype="出院记录"]//span[@itemid="1"]') else '无信息'
                    result[key_word]["医师"] = tree.xpath(
                        '//div[@esttype="入院记录"]//span[@itemid="2"]'
                    )[0].text.split("：")[1] if tree.xpath(
                        '//div[@esttype="入院记录"]//span[@itemid="2"]') else '无信息'
        return result

    def do_pacs(self, html_pacs):
        result = ''
        tree = etree.HTML(html_pacs)
        kind_list = tree.xpath(f'//input[@name="标本类型"]/@value')

        dio_list = tree.xpath(f'//input[@name="结论"]/@value')

        if kind_list and dio_list:
            kind_list = [x.split("()")[0] for x in kind_list]
            dio_list = [x.replace('\n', '') for x in dio_list]
            result_list = list(zip(kind_list, dio_list))
            result_list = ["：".join(x) for x in result_list]
            result = " ".join(result_list)

        return result


def to_word(result_json):
    # 将获取的信息存为word文档以便打印 2021年2月01日 19 时 00 分至2021年2月2日08 时 00 分
    file_kind = ''
    cur_date = datetime.datetime.strftime(datetime.datetime.today(),
                                          "%Y{}%m{}%d{}").format(
                                              "年", "月", "日")
    one_day = datetime.timedelta(days=1)
    past_date = datetime.datetime.strftime(datetime.datetime.today() - one_day,
                                           "%Y{}%m{}%d{}").format(
                                               "年", "月", "日")

    cur_hour = int(time.strftime("%H", time.localtime()))
    if cur_hour >= 12:
        file_kind = "白班"
        time_string = "%s 08时00分至%s 19时00分" % (cur_date, cur_date)
    else:
        file_kind = "夜班"
        time_string = "%s 19时00分至%s 08时00分" % (past_date, cur_date)
    patient_statistic = "原住院人数 人、入院 %s人、转入 0 人、转出 0 人、出院  人、手术 0 人、操作 0人、抢救 0 人、病危（病重） 0 人、死亡 0 人、危急值 0 人、输血 0 人、现住院人数 人。"

    # if os.path.isfile('.\\shift_mod_done.docx'):
    #     os.remove('.\\shift_mod_done.docx')

    shift_mod = Document(".\\mydocx\\shift.docx")

    t = shift_mod.tables[0]
    t.rows[0].cells[1].text = time_string

    if len(result_json) > 1:
        flag = True
    else:
        flag = False

    for k, v in result_json.items():
        if flag:
            new_row = deepcopy(t.rows[-3])
            t.rows[-2]._tr.addprevious(new_row._element)
        t.rows[-4].cells[0].text = v.setdefault('床号', '无信息')
        t.rows[-4].cells[1].text = v.setdefault('姓名', '无信息')
        t.rows[-4].cells[2].text = v.setdefault('性别', '无信息')
        t.rows[-4].cells[3].text = v.setdefault('年龄', '无信息')
        t.rows[-4].cells[4].text = '新入'
        t.rows[-4].cells[
            5].text = '%s 患儿以“%s”为代主诉入院 查体：%s %s 初步诊断：%s 治疗：%s 下班密切注意患儿病情变化。' % (
                v.setdefault('入院时间', '').split()[1] if v.setdefault(
                    '入院时间', '') else '无信息',
                v.setdefault('主诉', '无信息'),
                v.setdefault('TPRBP', '无信息'),
                v.setdefault('入院体检', '无信息'),
                v.setdefault('诊断', '无信息'),
                re.sub(r"请陈志鑫中医主治医师.+?治疗。", '', v.setdefault('诊疗计划', '无信息')[1])
            if v.setdefault('诊疗计划', '') else "无信息",
            )

    t.rows[1].cells[1].text = patient_statistic % (str(len(result_json)))
    # 删除倒数第三行
    t.rows[-3]._element.getparent().remove(t.rows[-3]._element)
    t.rows[-1].cells[-2].text = "       交班医师签名：陈白璐"
    # 白班、夜班的接班医师各有不同
    if file_kind == "白班":
        t.rows[-1].cells[-1].text = "接班医师签名：张伟东"
    else:
        t.rows[-1].cells[-1].text = "接班医师签名：陈志鑫"
    if not os.path.exists('交班报告'):
        os.mkdir('交班报告')
    random_file_name = ''.join(
        random.sample(string.ascii_letters + string.digits, 4))

    shift_mod.save('.\\交班报告\\%s%s%s.docx' %
                   (cur_date, file_kind, random_file_name))
    os.startfile('.\\交班报告\\%s%s%s.docx' %
                 (cur_date, file_kind, random_file_name))


def save_to_word(text_info):
    date_to_write = text_info['入院时间'].split()[0]
    d = Document('.\\mydocx\\a_notification.docx')

    # 获取word文档内的表格列表
    t = d.tables
    # 第一个表格为病人基本信息，包括姓名、性别、年龄
    t1 = t[0]

    # 姓名值位于t1.cell(0, 1)，即第一行第2列；
    run = t1.cell(0, 1).paragraphs[0].add_run(text_info['姓名'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 性别值位于t1.cell(0, 3)，即第一行第4列；
    run = t1.cell(0, 4).paragraphs[0].add_run(text_info['性别'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 年龄值位于t1.cell(0, 5)，即第一行第6列；
    run = t1.cell(0, 6).paragraphs[0].add_run(text_info['年龄'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 身份证号
    run = t1.cell(1, 1).paragraphs[0].add_run(text_info['身份证明号'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 住院号
    run = t1.cell(2, 1).paragraphs[0].add_run(text_info['住院号'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 诊断
    run = t1.cell(2, 4).paragraphs[0].add_run(text_info['诊断'])
    run.font.name = '宋体'
    run.font.size = 140000
    # 入院时间
    run = t1.cell(3, 4).paragraphs[0].add_run(date_to_write)
    run.font.name = '宋体'
    run.font.size = 140000
    # 时间1
    run = t1.cell(6, 5).paragraphs[0].add_run(date_to_write)
    run.font.name = '宋体'
    run.font.size = 140000
    # 时间2
    run = t1.cell(8, 3).paragraphs[0].add_run(date_to_write)
    run.font.name = '宋体'
    run.font.size = 140000
    if not os.path.exists('temp'):
        os.mkdir('temp')
    random_file_name1 = ''.join(
        random.sample(string.ascii_letters + string.digits, 8))

    d.save('.\\temp\\%s.docx' % random_file_name1)
    # 调试
    # os.startfile(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))
    print_file(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))
    random_file_name2 = ''.join(
        random.sample(string.ascii_letters + string.digits, 8))
    d.save('.\\temp\\%s.docx' % random_file_name2)
    print_file(os.path.abspath('.\\temp\\%s.docx' % random_file_name2))


def dio_report(text_info):
    # 生成诊断证明
    d = Document('.\\mydocx\\诊断证明模板.docx')

    # 获取word文档内的表格列表
    t = d.tables
    # 第一个表格为病人基本信息，包括姓名、性别、年龄
    t1 = t[0]

    info_0 = "科别：儿童消化心血管科  姓名：%s  性别：%s  年龄：%s 住院号：%s" % (
        text_info["姓名"],
        text_info["性别"],
        text_info["年龄"],
        text_info["住院号"],
    )
    run = t1.cell(0, 0).paragraphs[0].add_run(info_0)
    run.font.name = '宋体'
    run.font.size = 140000

    info_1 = "工作单位或家庭地址：%s" % (text_info["现住址"])
    run = t1.cell(1, 0).paragraphs[0].add_run(info_1)
    run.font.name = '宋体'
    run.font.size = 140000

    info_2 = "门诊就诊日期：%s" % (text_info["入院时间"].split()[0])
    run = t1.cell(2, 0).paragraphs[0].add_run(info_2)
    run.font.name = '宋体'
    run.font.size = 140000

    info_3 = "入院日期：%s  出院日期：%s" % (
        text_info["入院时间"].split()[0], text_info["出院日期"] if text_info["出院日期"] !=
        "无信息" else time.strftime("%Y.%m.%d", time.localtime()))
    run = t1.cell(3, 0).paragraphs[0].add_run(info_3)
    run.font.name = '宋体'
    run.font.size = 140000

    info_5 = text_info[
        "入院情况(出院记录)"] if text_info["入院情况(出院记录)"] != "无信息" else '-'
    run = t1.cell(5, 0).paragraphs[0].add_run(info_5)
    run.font.name = '宋体'
    run.font.size = 140000

    info_7 = text_info["出院诊断"] if text_info["出院诊断"] != "无信息" else text_info[
        "诊断"]
    run = t1.cell(7, 0).paragraphs[0].add_run(info_7)
    run.font.name = '宋体'
    run.font.size = 140000

    info_9 = text_info[
        "出院医嘱"] if text_info["出院医嘱"] != "无信息" else "继续口服药物巩固治疗，1周后复诊，不适随诊。"
    run = t1.cell(9, 0).paragraphs[0].add_run(info_9)
    run.font.name = '宋体'
    run.font.size = 140000

    info_11 = text_info[
        "出院日期"] if text_info["出院日期"] != "无信息" else time.strftime(
            "%Y.%m.%d", time.localtime())
    run = t1.cell(11, 0).paragraphs[0].add_run(info_11)
    run.font.name = '宋体'
    run.font.size = 140000
    save_name = "%s_%s" % (time.strftime("%Y%m%d",
                                         time.localtime()), text_info["姓名"])

    if not os.path.exists('E:\\诊断证明'):
        os.mkdir('E:\\诊断证明')                                        
    d.save('E:\\诊断证明\\%s.docx' % save_name)
    os.startfile('E:\\诊断证明\\%s.docx' % save_name)
    # print_file(os.path.abspath('E:\\诊断证明\\%s.docx' % save_name))


def lclj_dbz(text_info):
    # 生成临床路径
    d = Document('.\\mydocx\\支肺临床路径.docx')

    # 获取word文档内的表格列表
    t = d.tables
    # 第一个表格为病人基本信息，包括姓名、性别、年龄
    t1 = t[0]

    info_0 = "患者姓名：%s 性别：%s 年龄：%s 门诊号：       住院号：%s" % (
        text_info["姓名"],
        text_info["性别"],
        text_info["年龄"],
        text_info["住院号"],
    )
    run = t1.cell(0, 0).paragraphs[0].add_run(info_0)
    run.font.name = '宋体'
    run.font.size = 140000

    info_1 = "住院日期：%s 出院日期：%s 标准住院日： 7–14天" % (text_info["入院时间"].split(
    )[0], text_info["出院日期"] if text_info["出院日期"] != "无信息" else "        ")
    run = t1.cell(1, 0).paragraphs[0].add_run(info_1)
    run.font.name = '宋体'
    run.font.size = 140000
    random_file_name1 = ''.join(
        random.sample(string.ascii_letters + string.digits, 8))
    if not os.path.exists('temp'):
        os.mkdir('temp')
    d.save('.\\temp\\%s.docx' % random_file_name1)
    # 调试
    # os.startfile(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))
    print_file(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))

    #单病种
    d1 = Document('.\\mydocx\\支肺单病种.docx')

    # 获取word文档内的表格列表
    t = d1.tables
    # 第一个表格为病人基本信息，包括姓名、性别、年龄
    t1 = t[0]

    info_0 = "姓名：%s 性别：%s 年龄：%s 病案号：%s入院日期：%s 出院日期：%s" % (
        text_info["姓名"], text_info["性别"], text_info["年龄"], text_info["住院号"],
        text_info["入院时间"].split()[0],
        text_info["出院日期"] if text_info["出院日期"] != "无信息" else "        ")
    run = t1.cell(1, 0).paragraphs[0].add_run(info_0)
    run.font.name = '宋体'
    run.font.size = 140000

    random_file_name2 = ''.join(
        random.sample(string.ascii_letters + string.digits, 8))
    d1.save('.\\temp\\%s.docx' % random_file_name2)
    print_file(os.path.abspath('.\\temp\\%s.docx' % random_file_name2))


def in_and_out(result_json):
    in_and_out_mod = Document(".\\mydocx\\in_and_out.docx")

    t = in_and_out_mod.tables[0]

    contents = [
        '住院号', '姓名', '性别', '年龄', '医师', '入院情况', '出院诊断', '入院日期', '出院日期', '治疗效果',
        '联系人地址', '联系人电话'
    ]
    for k, v in result_json.items():

        t.add_row()
        for idx, kys in enumerate(contents):

            if kys == '治疗效果':
                t.rows[-1].cells[idx].text = '治愈'
            else:
                t.rows[-1].cells[idx].text = v.setdefault(kys, '无信息').strip()

    if not os.path.exists('出入院登记本'):
        os.mkdir('出入院登记本')
    random_file_name = time.strftime('%Y-%m-%d_%H%M%S', time.localtime())

    in_and_out_mod.save('.\\出入院登记本\\%s.docx' % random_file_name)
    os.startfile('.\\出入院登记本\\%s.docx' % random_file_name)


class DifDiagnosis(tk.Toplevel):
    def __init__(self):
        self.result = ''
        super().__init__()
        self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 550
        wh = 400
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('鉴别诊断')
        tk.Label(self, text='鉴别诊断').grid(sticky="w" + "e")
        with open('.\\myjson\\dif_diagnosis.json', 'r', encoding='utf-8') as f:
            dif_diagnosis = json.load(f)

        self.curriculum = dif_diagnosis
        self.var = {}
        row_idx = 1
        col_idx = 0
        for k, v in self.curriculum.items():
            self.var[k] = tk.BooleanVar()
            tk.Checkbutton(self, text=k,
                           variable=self.var[k]).grid(row=row_idx,
                                                      column=col_idx,
                                                      sticky="w")
            col_idx += 1
            if col_idx > 3:
                row_idx += 1
                col_idx = 0
        btn_frame = tk.Frame(self)
        btn_frame.grid(row=row_idx + 1, columnspan=5)
        tk.Button(btn_frame,
                  text='确认',
                  command=self.confirm,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx + 1,
                                        column=0,
                                        columnspan=2)

        tk.Button(btn_frame,
                  text='退出',
                  command=self.cancel,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx + 1,
                                        column=3,
                                        columnspan=2)

    def cancel(self):
        self.destroy()

    def confirm(self):
        select = ''
        idx = 1
        for k, v in self.var.items():
            if v.get():
                # select += '%d.%s：%s;' % (idx, k, self.curriculum[k])
                select += '%s：%s;' % (k, self.curriculum[k])
                idx += 1

        pyperclip.copy(select)
        self.result = select
        self.destroy()


# 选择症状界面
class Symptom(tk.Toplevel):
    def __init__(self):
        self.result = ''
        super().__init__()
        self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 550
        wh = 400
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('选择症状')
        tk.Label(self, text='症状').grid(sticky="w" + "e")
        with open('.\\myjson\\symptom_select.json', 'r', encoding='utf-8') as f:
            symptom = json.load(f)

        self.curriculum = symptom
        self.var = {}
        row_idx = 1
        col_idx = 0
        for k, v in self.curriculum.items():
            self.var[k] = tk.BooleanVar()
            tk.Checkbutton(self, text=k,
                           variable=self.var[k]).grid(row=row_idx,
                                                      column=col_idx,
                                                      sticky="w")
            col_idx += 1
            if col_idx > 3:
                row_idx += 1
                col_idx = 0
        btn_frame = tk.Frame(self)
        btn_frame.grid(row=row_idx + 1, columnspan=5)
        tk.Button(btn_frame,
                  text='确认',
                  command=self.confirm,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx + 1,
                                        column=0,
                                        columnspan=2)

        tk.Button(btn_frame,
                  text='退出',
                  command=self.cancel,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx + 1,
                                        column=3,
                                        columnspan=2)

    def cancel(self):
        self.destroy()

    def confirm(self):
        for k, v in self.var.items():
            if v.get():

                self.result += self.curriculum[k]

        self.destroy()


# 自备药品
def drug_bought_by_patient(text_info, drug_selected):

    for drug in drug_selected:
        info_to_fill = {
            (0, 1): text_info['姓名'],  # 姓名
            (0, 5): text_info['性别'],  # 性别
            (0, 9): text_info['年龄'],  # 年龄
            (1, 1): text_info['病房'],  # 科室
            (1, 5): text_info['床号'],  # 床号
            (1, 9): text_info['住院号'],  # 住院号
            (2, 1): text_info['诊断'],  # 诊断
        }
        x = 4
        info_to_fill[(x, 1)] = drug['药品名称']
        info_to_fill[(x, 2)] = drug['规格']
        info_to_fill[(x, 4)] = drug['批号']
        info_to_fill[(x, 6)] = drug['数量']
        info_to_fill[(x, 8)] = drug['厂家']
        info_to_fill[(x, 10)] = drug['途径']
        info_to_fill[(7, 1)] = drug['用途']

        d = Document('.\\mydocx\\自备药品.docx')
        t = d.tables
        t1 = t[0]

        for cell_cord, cell_content in info_to_fill.items():
            run = t1.cell(*(cell_cord)).paragraphs[0].add_run(cell_content)
            run.font.name = '宋体'
            run.font.size = 140000
        save_name = "%s_%s" % (drug['药品名称'], text_info["姓名"])
        if not os.path.exists('e:\\自备药品'):
            os.mkdir('e:\\自备药品')
        d.save('e:\\自备药品\\%s.docx' % save_name)
        # os.startfile('e:\\自备药品\\%s.docx' % save_name)
        print_file(os.path.abspath('e:\\自备药品\\%s.docx' % save_name))
        info_to_fill = {}


# 自备药品界面
class DrugBought(tk.Toplevel):
    def __init__(self, text_info):
        self.result = []
        self.text_info = text_info
        super().__init__()
        self.wm_attributes('-topmost', 1)

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 550
        wh = 400
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('选择自备药品')
        tk.Label(self, text='自备药品').grid(sticky="w" + "e")
        with open('.\\myjson\\drug_bought_by_pt.json', 'r', encoding='utf-8') as f:
            data_load = json.load(f)

        self.curriculum = data_load
        self.var = {}
        row_idx = 1
        col_idx = 0
        for k, v in self.curriculum.items():
            self.var[k] = tk.BooleanVar()
            tk.Checkbutton(self, text=k,
                           variable=self.var[k]).grid(row=row_idx,
                                                      column=col_idx,
                                                      sticky="w")
            row_idx += 1

        btn_frame = tk.Frame(self)
        btn_frame.grid(row=row_idx + 1, columnspan=5)
        tk.Button(btn_frame,
                  text='确认',
                  command=self.confirm,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx + 1,
                                        column=0,
                                        columnspan=2)

        tk.Button(btn_frame,
                  text='退出',
                  command=self.cancel,
                  width=12,
                  height=1,
                  activebackground='grey',
                  relief='groove').grid(row=row_idx + 1,
                                        column=3,
                                        columnspan=2)

    def cancel(self):
        self.destroy()

    def confirm(self):
        for k, v in self.var.items():
            if v.get():

                self.result.append(self.curriculum[k])
        drug_bought_by_patient(self.text_info, self.result)
        self.destroy()


# 病人信息界面
class PatientInfo(tk.Toplevel):
    def __init__(self, patient_info):

        self.patient_info = patient_info
        super().__init__()
        self.wm_attributes('-topmost', 1)
        self.attributes('-alpha', 0.5)
        self.bind('<Enter>', self.show)
        self.bind('<Leave>', self.hide)
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 400
        wh = 1000
        self.geometry("%dx%d+%d+%d" % (ww, wh, sw - ww, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('病人信息')
        info_frame = tk.Frame(self)
        info_frame.pack()
        self.patient_name = tk.StringVar()
        self.patient_id = tk.StringVar()
        self.date_formater = tk.StringVar()
        self.date_info = tk.StringVar()
        self.patient_name.set(self.patient_info['姓名'])
        self.patient_id.set(self.patient_info['住院号'])
        name_label = tk.Label(info_frame, textvariable=self.patient_name)
        name_label.pack(side=tk.LEFT, padx=5)
        self.id_entry = tk.Entry(info_frame,
                                 textvariable=self.patient_id,
                                 width=10)
        self.id_entry.bind('<Enter>', self.select_all)
        self.id_entry.bind('<Return>', self.re_frash)
        self.id_entry.focus_set()
        self.id_entry.pack(side=tk.LEFT, padx=5)
        frash_btn = tk.Button(info_frame,
                              text='更新',
                              activebackground='grey',
                              width=5,
                              relief='groove')
        frash_btn.bind('<ButtonRelease-1>', self.re_frash)
        frash_btn.pack(side=tk.LEFT, padx=5)
        self.date_entry = tk.Entry(info_frame,
                                   textvariable=self.date_formater,
                                   width=10)
        self.date_entry.bind('<Enter>', self.select_all)
        self.date_entry.bind('<Return>', self.date_format)
        self.date_entry.pack(side=tk.LEFT, padx=5)
        tk.Label(
            info_frame,
            textvariable=self.date_info,
        ).pack(side=tk.LEFT, padx=5)
        self.radio_genarator()
        btn_cancel = tk.Button(self,
                               text='退出',
                               command=self.cancel,
                               width=12,
                               height=1,
                               activebackground='grey',
                               relief='groove')
        btn_cancel.pack(side=tk.BOTTOM)

    def radio_genarator(self):
        self.flag = tk.StringVar()
        self.flag.set('姓名')
        self.radio_frame = tk.Frame(self)
        self.radio_frame.pack()
        key_words = [
            '姓名', '性别', '年龄', '住院号', '床号', '身份证明号', '现住址', '联系人姓名', '联系人电话',
            '入院日期', '出院日期', '医师', '诊断', '出院诊断', '主诉', '病史', '现病史', 'TPRBP',
            '入院体检', '入院化验单', '病人简介', '病例特点', '化验单', '影像学', '入院情况(出院记录)',
            '诊疗经过', '出院情况', '出院医嘱'
        ]
        for key_word in key_words:
            v_ = self.patient_info.setdefault(key_word, '无信息')

            tk.Radiobutton(
                self.radio_frame,
                variable=self.flag,
                text='%s：%s' %
                (key_word, v_ if key_word not in [
                    '病史', '主诉', '现病史', '入院体检', 'TPRBP', '入院化验单', '病例特点', '化验单',
                    '影像学', '入院情况(出院记录)', '诊疗经过', '出院情况', '出院医嘱'
                ] else '%s...%s' %
                 (v_[:int(len(v_)) if int(len(v_)) < 10 else 10],
                  v_[-(int(len(v_)) if int(len(v_)) < 10 else 10):])),
                value=v_,
                command=self.on_select).pack(anchor=tk.W, padx=10)
        for idx, v in enumerate(self.patient_info.setdefault('诊疗计划', [])):
            tk.Radiobutton(self.radio_frame,
                           variable=self.flag,
                           text='%s：%s' % ('诊疗计划%s' %
                                           (idx + 1), '%s...' % v[:20]),
                           value=v,
                           command=self.on_select).pack(anchor=tk.W, padx=10)

        self.btn_frame = tk.Frame(self)
        self.btn_frame.pack()

        btn_fzr = tk.Button(self.btn_frame,
                            text='副主任',
                            command=self.fzr,
                            width=6,
                            height=1,
                            activebackground='grey',
                            relief='groove')
        btn_fzr.pack(padx=5, side=tk.LEFT)

        btn_zr = tk.Button(self.btn_frame,
                           text='主任',
                           command=self.zr,
                           width=6,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_zr.pack(padx=5, side=tk.LEFT)

        btn_hyd = tk.Button(self.btn_frame,
                            text='化验单',
                            command=self.hyd,
                            width=6,
                            height=1,
                            activebackground='grey',
                            relief='groove')
        btn_hyd.pack(padx=5, side=tk.LEFT)

        btn_lclj = tk.Button(self.btn_frame,
                             text='临床路径',
                             command=self.lclj,
                             width=6,
                             height=1,
                             activebackground='grey',
                             relief='groove')
        btn_lclj.pack(padx=5, side=tk.LEFT)

        btn_dif_diagnosis = tk.Button(self.btn_frame,
                                      text='鉴别',
                                      command=self.dif_diagnosis,
                                      width=6,
                                      height=1,
                                      activebackground='grey',
                                      relief='groove')
        btn_dif_diagnosis.pack(padx=5, side=tk.LEFT)

        self.btn_frame1 = tk.Frame(self)
        self.btn_frame1.pack()
        btn_yb = tk.Button(self.btn_frame1,
                           text='医保',
                           command=self.yb,
                           width=6,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_yb.pack(padx=5, side=tk.LEFT)
        btn_zdz = tk.Button(self.btn_frame1,
                            text='诊断证',
                            command=self.zdz,
                            width=6,
                            height=1,
                            activebackground='grey',
                            relief='groove')
        btn_zdz.pack(padx=5, side=tk.LEFT)
        btn_drug_bought = tk.Button(self.btn_frame1,
                                    text='自备药品',
                                    command=self.drug_bought,
                                    width=6,
                                    height=1,
                                    activebackground='grey',
                                    relief='groove')
        btn_drug_bought.pack(padx=5, side=tk.LEFT)
        btn_na = tk.Button(self.btn_frame1,
                           text='营养评估',
                           command=self.na,
                           width=6,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_na.pack(padx=5, side=tk.LEFT)
        btn_cmc = tk.Button(self.btn_frame1,
                           text='沟通',
                           command=self.cmc,
                           width=6,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_cmc.pack(padx=5, side=tk.LEFT)

        btn_zyhz = tk.Button(self.btn_frame1,
                           text='会诊',
                           command=self.zyhz,
                           width=6,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_zyhz.pack(padx=5, side=tk.LEFT)

    def show(self, event):
        self.attributes('-alpha', 1.0)
        self.update()

    def hide(self, event):
        self.attributes('-alpha', 0.5)
        self.update()

    def on_select(self):
        pyperclip.copy(self.flag.get())

    def select_all(self, event):
        # event.widget 即触发事件的控件，可以直接用它的方法如.select_range()等
        event.widget.select_range(0, tk.END)

    def cancel(self):
        self.destroy()

    def drug_bought(self):
        drug_bought_window = DrugBought(self.patient_info)
        self.wait_window(drug_bought_window)

    def dif_diagnosis(self):
        dif_diagnosis_window = DifDiagnosis()
        self.wait_window(dif_diagnosis_window)
        self.state('icon')

    def lclj(self):
        lclj_dbz(self.patient_info)

    def date_format(self, event):
        date_get = self.date_formater.get()
        try:
            date_formated = datetime.datetime.strptime(date_get, '%Y.%m.%d %H：%M')
            date_formated = datetime.datetime.strftime(date_formated, '%Y年%m月%d日 %H时%M分')

            pyperclip.copy(date_formated)
        except Exception as e:
            self.date_info.set('输入出错！')
            self.update()
        event.widget.select_range(0, tk.END)

    def re_frash(self, event):
        self.patient_name.set("查询中...")
        self.state('icon')
        self.update()
        new_patient_id = self.patient_id.get()
        pyperclip.copy(new_patient_id)
        query_app = AcquireInfoTotal(new_patient_id)
        query_list = ['病程记录', 'LIS报告单', 'PACS报告单']
        pool = Pool(3)
        query_result = pool.map(query_app.query_content, query_list)
        query_dic = {}
        for each_result in query_result:
            query_dic.update(each_result)
        data_resolved = DataResolver(query_app.pid)
        data_resolved.record_resolve(query_dic)

        if data_resolved.patient_info:
            self.patient_info = data_resolved.patient_info
        self.patient_name.set(self.patient_info['姓名'])
        self.patient_id.set(self.patient_info['住院号'])
        self.radio_frame.destroy()
        self.btn_frame.destroy()
        self.btn_frame1.destroy()
        self.radio_genarator()
        # event.widget.select_range(0, tk.END)
        self.update()
        self.state('normal')
        self.update()

    def yb(self):
        # save_to_word(self.patient_info)

        print_file(os.path.abspath('.\\mydocx\\bcnotification.docx'))

    def zdz(self):
        dio_report(self.patient_info)

    def fzr(self):
        sym = Symptom()
        self.wait_window(sym)
        difdiag = DifDiagnosis()
        self.wait_window(difdiag)
        if not sym.result:
            normal_ = '患儿体温正常，无呕吐，无腹泻，无腹痛，无咳嗽、气喘、呼吸困难，无皮疹，食欲及夜眠一般，大小便正常'
        else:
            normal_ = sym.result
        tprbp = utils.form_TPRBP(age=self.patient_info['年龄'],
                                 copy_flag=False).rstrip(" W：")
        tprbp_list = tprbp.split()
        p = tprbp_list[1]
        pys_exam = re.sub(r'(心率)(\d+)次/分', lambda x: x.group(1) + p,
                          self.patient_info.setdefault('入院体检', '无信息'))
        # 副主任医师查房                  
        mod = "今日查房，%s，查体：%s %s 王亚妮副主任医师查房仔细询问病史：%s %s 入院查体：%s %s 辅助检查：%s 根据以上资料，王亚妮副主任医师考虑诊断为%s 鉴别诊断：%s 治疗：%s 继续完善相关检查明确诊断，嘱合理饮食：忌食生冷辛辣油腻食物，清淡、优质蛋白饮食。观察病情变化。上级医师查房意见已执行。患儿及陪护家属无新冠病毒感染症状,新冠病毒核酸检测均阴性，均排除新冠病毒感染。"
        # 自己查房
        mod = "今日查房，%s，查体：%s %s 回顾病史：%s %s 入院查体：%s %s 辅助检查：%s 根据以上资料，目前考虑诊断为%s 鉴别诊断：%s 治疗：%s 继续完善相关检查明确诊断，嘱合理饮食：忌食生冷辛辣油腻食物，清淡、优质蛋白饮食。观察病情变化。患儿及陪护家属无新冠病毒感染症状,新冠病毒核酸检测均阴性，均排除新冠病毒感染。"
        result = mod % (
            normal_,
            tprbp,
            pys_exam,
            self.patient_info.setdefault('病人简介', '无信息'),
            self.patient_info.setdefault('病例特点', '无信息'),
            self.patient_info.setdefault('TPRBP', '无信息'),
            self.patient_info.setdefault('入院体检', '无信息'),
            self.patient_info.setdefault('入院化验单', '无信息'),
            self.patient_info.setdefault('诊断', '无信息'),
            difdiag.result,
            re.sub(r"请陈志鑫中医主治医师.+?治疗。", '', self.patient_info.setdefault('诊疗计划', '无信息')[1])
            if self.patient_info.setdefault('诊疗计划', '') else "无信息",
        )
        pyperclip.copy(result)
        self.state('icon')

    def zr(self):
        sym = Symptom()
        self.wait_window(sym)
        difdiag = DifDiagnosis()
        self.wait_window(difdiag)
        if not sym.result:
            normal_ = '患儿体温正常，无呕吐，无腹泻，无腹痛，无咳嗽、气喘、呼吸困难，无皮疹，食欲及夜眠一般，大小便正常'
        else:
            normal_ = sym.result
        tprbp = utils.form_TPRBP(age=self.patient_info['年龄'],
                                 copy_flag=False).rstrip(" W：")
        tprbp_list = tprbp.split()
        p = tprbp_list[1]
        pys_exam = re.sub(r'(心率)(\d+)次/分', lambda x: x.group(1) + p,
                          self.patient_info.setdefault('入院体检', '无信息'))
        mod_zr = "汇报病史：%s %s 入院查体：%s %s 入院前检查：%s 陈芳主任医师查房：%s 查体：%s %s 辅助检查：%s %s 根据患儿病史、临床表现、体征及辅助检查，目前诊断考虑：%s 应与以下疾病鉴别：%s 治疗：%s 嘱病房勤开窗通风，勤饮水扣背，清淡饮食。观察病情变化。上级医师查房意见已执行。患儿及陪护家属无新冠病毒感染症状,新冠病毒核酸检测均阴性，均排除新冠病毒感染。"
        result_zr = mod_zr % (
            self.patient_info.setdefault('病人简介', '无信息'),
            self.patient_info.setdefault('病例特点', '无信息'),
            self.patient_info.setdefault('TPRBP', '无信息'),
            self.patient_info.setdefault('入院体检', '无信息'),
            self.patient_info.setdefault('入院化验单', '无信息'),
            normal_,
            tprbp,
            pys_exam,
            self.patient_info.setdefault('化验单', '无信息'),
            self.patient_info.setdefault('影像学', '无信息'),
            self.patient_info.setdefault('诊断', '无信息'),
            difdiag.result,
            re.sub(r"请陈志鑫中医主治医师.+?治疗。", '', self.patient_info.setdefault('诊疗计划', '无信息')[1])
            if self.patient_info.setdefault('诊疗计划', '') else "无信息",
        )
        pyperclip.copy(result_zr)
        self.state('icon')

    #营养评估
    def hyd(self):
        hyd_manully.hyd()
    def cmc(self):
        cmc_window = comunacation.CMC(self.patient_info)
        self.wait_window(cmc_window)
    def zyhz(self):
        zyhz_window = cn_consult.ZYHZ(self.patient_info)
    
        self.wait_window(zyhz_window)
    def na(self):
        info_to_fill_1 = '住院号：%s    姓名：%s    性别：%s    年龄：%s    病区：儿童消化心血管科 床号：%s' % (
            self.patient_info.setdefault('住院号', '无信息'),
            self.patient_info.setdefault('姓名', '无信息'),
            self.patient_info.setdefault('性别', '无信息'),
            self.patient_info.setdefault('年龄', '无信息'),
            self.patient_info.setdefault('床号', '无信息'),
        )

        info_to_fill_2 = '医师签字：                          测评日期：%s' % self.patient_info.setdefault(
            '记录时间', '无信息')
        d = Document('.\\mydocx\\nutrition_assessment.docx')

        # 获取word文档内的表格列表
        t = d.tables
        # 第一个表格
        t1 = t[0]
        run = t1.cell(0, 0).paragraphs[0].add_run(info_to_fill_1)
        run.font.name = '宋体'
        run.font.size = 140000
        # 第二个表格
        t2 = t[1]
        run = t2.cell(0, 0).paragraphs[0].add_run(info_to_fill_2)
        run.font.name = '宋体'
        run.font.size = 140000
        if not os.path.exists('temp'):
            os.mkdir('temp')
        random_file_name = ''.join(
            random.sample(string.ascii_letters + string.digits, 8))

        d.save('.\\temp\\%s.docx' % random_file_name)
        # 调试
        # os.startfile(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))
        print_file(os.path.abspath('.\\temp\\%s.docx' % random_file_name))


# 主UI
class MainWindow(tk.Tk):
    def __init__(self):
        self.text_path = ''
        super().__init__()
        # self.wm_attributes('-topmost', 1)
        self.attributes('-alpha', 0.5)
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        ww = 600
        wh = 150
        self.geometry("%dx%d+%d+%d" % (ww, wh, (sw - ww) / 2, (sh - wh) / 2))
        self.after(1, lambda: self.focus_force())
        self.iconphoto(False, tk.PhotoImage(file='title.png'))
        self.title('pro v5.0 by cbl')
        self.flag = tk.StringVar()
        self.flag.set('病人信息')
        self.bind('<Enter>', self.show)
        self.bind('<Leave>', self.hide)
        radio_frame = tk.Frame(self)
        radio_frame.pack()
        tk.Radiobutton(radio_frame,
                       variable=self.flag,
                       text='病人信息',
                       value='病人信息').pack(side=tk.LEFT)
        tk.Radiobutton(radio_frame, variable=self.flag, text='交班',
                       value='交班').pack(side=tk.LEFT)
        tk.Radiobutton(radio_frame, variable=self.flag, text='医保',
                       value='医保').pack(side=tk.LEFT)
        tk.Radiobutton(radio_frame,
                       variable=self.flag,
                       text='诊断证',
                       value='诊断证').pack(side=tk.LEFT)

        tk.Radiobutton(
            radio_frame,
            variable=self.flag,
            text='出入院',
            value='出入院',
        ).pack(side=tk.LEFT)

        tk.Radiobutton(
            radio_frame,
            variable=self.flag,
            text='登记本',
            value='登记本',
        ).pack(side=tk.LEFT)

        tk.Radiobutton(
            radio_frame,
            variable=self.flag,
            text='营养评估',
            value='营养评估',
        ).pack(side=tk.LEFT)

        self.info = tk.StringVar()
        self.info.set('请输入住院号或放入txt文件')

        self.f = tk.Frame(self)
        self.f.pack()

        self.info_label = tk.Label(
            self.f,
            textvariable=self.info,
            font=('微软雅黑', 10),
        )

        self.info_label.pack()
        self.pid = tk.StringVar()
        for_pid = pyperclip.paste()
        if for_pid:
            self.pid.set(for_pid)
        else:
            self.pid.set('21000000 21000001')
        self.pid_e = tk.Entry(
            self.f,
            width=60,
            textvariable=self.pid,
            relief='groove',
            font=('微软雅黑', 10),
            selectbackground='brown',
        )

        windnd.hook_dropfiles(self.pid_e.winfo_id(), self.fuc)
        self.pid_e.bind('<FocusIn>', self.on_select)
        self.pid_e.bind('<Enter>', self.on_select)
        self.pid_e.bind('<Return>', self.submit)
        self.pid_e.focus_set()
        self.pid_e.pack()

        btn_frame = tk.Frame(self)
        btn_frame.pack(pady=10)
        btn_ok = tk.Button(btn_frame,
                           text='确 定',
                           width=12,
                           height=1,
                           activebackground='grey',
                           relief='groove')
        btn_ok.bind('<ButtonRelease-1>', self.submit)
        btn_ok.pack(side=tk.LEFT)
        btn_cancel = tk.Button(btn_frame,
                               text='取消',
                               command=self.cancel,
                               width=12,
                               height=1,
                               activebackground='grey',
                               relief='groove')
        btn_cancel.pack(side=tk.RIGHT)

    def show(self, event):
        self.attributes('-alpha', 1.0)
        self.update()

    def hide(self, event):
        self.attributes('-alpha', 0.5)
        self.update()

    def submit(self, event):
        try:

            result_json = {}
            pid = self.pid.get()
            
            pyperclip.copy(pid)
            pid = pid.strip()
            if pid:
                self.state('icon')
                pid_list = pid.split()
                if pid_list[0].isdigit():
                    lines = pid_list

                else:
                    with open(
                            pid,
                            'r',
                    ) as f:
                        lines = f.readlines()

                for line in lines:
                    try:
                        if not line.isdigit():
                            line = line.split()[1].strip()

                        if line.isdigit():

                            self.info_label['fg'] = 'blue'
                            self.info.set('正在查询：【%s】' % line)
                            self.update()

                            query_app = AcquireInfoTotal(line)
                            
                            if self.flag.get() == '登记本':

                                query_dic = query_app.query_content()
                                data_resolved = DataResolver(query_app.pid)
                                result = data_resolved.check_keywords(
                                    query_dic, ['穿刺', '胃镜', '会诊记录'])
                                if result:
                                    result_json[line] = result
                            
                            else:
                                
                                if self.flag.get() =='病人信息':
                                    
                                    query_list = ['病程记录', 'LIS报告单', 'PACS报告单',]
                                    
                                    pool = Pool(3)
                                    
                                else:
                                    query_list = [
                                        '病程记录',
                                    ]
                                    pool = Pool(1)
                                
                                query_result = pool.map(
                                    query_app.query_content, query_list)
                              
                                
                                query_dic = {}
                                for each_result in query_result:
                                    query_dic.update(each_result)
                                
                                data_resolved = DataResolver(query_app.pid)
                                data_resolved.record_resolve(query_dic)
                                if data_resolved.patient_info:
                                    result_json[
                                        line] = data_resolved.patient_info
                    # except Exception as e:
                    except ValueError as e:
                        with open('.\\error_log\\errors.txt', 'a+',
                                  encoding='utf-8') as f_error:
                            f_error.write(f'{line} 错误信息：{e}\n')
                        self.info_label['fg'] = 'red'
                        self.info.set('出现错误')
                        self.update()
                        continue
                    # except ValueError as e:
                    #     pass
                if result_json:
                    self.info_label['fg'] = 'green'
                    self.info.set('查询结束，将自动打开查询结果，请慢用^_^')
                    self.update()

                    if self.flag.get() == '医保':
                        for v in result_json.values():
                            # save_to_word(v)

                            print_file(os.path.abspath('.\\mydocx\\bcnotification.docx'))

                    elif self.flag.get() == '诊断证':
                        for v in result_json.values():
                            dio_report(v)
                    elif self.flag.get() == '交班':
                        to_word(result_json)
                    elif self.flag.get() == '出入院':
                        in_and_out(result_json)
                    elif self.flag.get() == '病人信息':
                        for v in result_json.values():
                            patient_info_app = PatientInfo(v)
                            self.wait_window(patient_info_app)
                        # self.destroy()
                            
                    elif self.flag.get() == '登记本':
                        wb = openpyxl.load_workbook('.\\myxlsx\\operation_records.xlsx')
                        sh = wb.active
                        i = 3
                        wb_hz = openpyxl.load_workbook('.\\myxlsx\\会诊登记本.xlsx')
                        sh_hz = wb_hz.active
                        i_hz = 5
                        for each in result_json.values():
                            for kind, v in each.items():
                                if kind == '会诊记录':

                                    for k in v['results']:
                                        if k:

                                            sh_hz.cell(row=i_hz,
                                                       column=2,
                                                       value=v['姓名'])
                                            sh_hz.cell(row=i_hz,
                                                       column=3,
                                                       value=v['性别'])

                                            sh_hz.cell(row=i_hz,
                                                       column=4,
                                                       value=v['住院号'])
                                            sh_hz.cell(row=i_hz,
                                                       column=5,
                                                       value=v['出院诊断'])
                                            sh_hz.cell(row=i_hz,
                                                       column=6,
                                                       value=v['医师'])
                                            sh_hz.cell(row=i_hz,
                                                       column=7,
                                                       value='主治医师')
                                            sh_hz.cell(
                                                row=i_hz,
                                                column=15,
                                                value=k['record_result'])

                                            i_hz += 1
                                else:
                                    for k in v['results']:
                                        if k:
                                            sh.cell(row=i,
                                                    column=1,
                                                    value=k['date_result'])
                                            sh.cell(row=i,
                                                    column=2,
                                                    value=v['医师'])
                                            sh.cell(row=i,
                                                    column=3,
                                                    value=v['姓名'])
                                            sh.cell(row=i,
                                                    column=4,
                                                    value=v['性别'])
                                            sh.cell(row=i,
                                                    column=5,
                                                    value=v['年龄'])
                                            sh.cell(row=i,
                                                    column=6,
                                                    value=v['住院号'])
                                            sh.cell(row=i,
                                                    column=7,
                                                    value=k['name_result'])
                                            sh.cell(row=i,
                                                    column=8,
                                                    value=v['出院诊断'])
                                            sh.cell(row=i,
                                                    column=9,
                                                    value=k['date_result'])
                                            sh.cell(row=i,
                                                    column=11,
                                                    value=v['出院诊断'])
                                            sh.cell(row=i,
                                                    column=12,
                                                    value=k['record_result'])
                                            i += 1
                        wb.save(
                            f'.\\有创操作\\胃镜{time.strftime("%Y.%m.%d", time.localtime())}.xlsx'
                        )
                        wb_hz.save(
                            f'.\\有创操作\\会诊{time.strftime("%Y.%m.%d", time.localtime())}.xlsx'
                        )
                        tkinter.messagebox.showinfo('提示', '完成！')
                        os.startfile('.\\有创操作')
                    elif self.flag.get() == '营养评估':
                        for v in result_json.values():
                            patient_info = v
                            info_to_fill_1 = '住院号：%s    姓名：%s    性别：%s    年龄：%s      病区：儿童消化心血管科 床号：%s' % (
                                patient_info.setdefault('住院号', '无信息'),
                                patient_info.setdefault('姓名', '无信息'),
                                patient_info.setdefault('性别', '无信息'),
                                patient_info.setdefault('年龄', '无信息'),
                                patient_info.setdefault('床号', '无信息'),
                            )

                            info_to_fill_2 = '医师签字：                             测评日期：%s' % patient_info.setdefault(
                                '记录时间', '无信息')
                            d = Document('.\\nutrition_assessment.docx')

                            # 获取word文档内的表格列表
                            t = d.tables
                            # 第一个表格
                            t1 = t[0]
                            run = t1.cell(
                                0, 0).paragraphs[0].add_run(info_to_fill_1)
                            run.font.name = '宋体'
                            run.font.size = 140000
                            # 第二个表格
                            t2 = t[1]
                            run = t2.cell(
                                0, 0).paragraphs[0].add_run(info_to_fill_2)
                            run.font.name = '宋体'
                            run.font.size = 140000
                            if not os.path.exists('temp'):
                                os.mkdir('temp')
                            random_file_name = ''.join(
                                random.sample(
                                    string.ascii_letters + string.digits, 8))

                            d.save('.\\temp\\%s.docx' % random_file_name)
                            # 调试
                            # os.startfile(os.path.abspath('.\\temp\\%s.docx' % random_file_name1))
                            print_file(
                                os.path.abspath('.\\temp\\%s.docx' %
                                                random_file_name))
                    
            else:
                self.info_label['fg'] = 'red'
                self.info.set('住院号无效！')
                self.state('normal')
        except PermissionError:
            self.info_label['fg'] = 'red'
            self.info.set('运行出错：临时文件被占用！\n请关闭程序自动打开的所有word文件后重试！')
            self.state('normal')
        # except ValueError:
        #     self.info_label['fg'] = 'red'
        #     self.info.set('住院号无效！')
        #     self.pid.set('')

    def on_select(self, event):
        # event.widget 即触发事件的控件，可以直接用它的方法如.select_range()等
        event.widget.select_range(0, tk.END)

    def cancel(self):
        try:
            if os.path.isdir('.\\temp\\'):
                shutil.rmtree('.\\temp\\')
            self.destroy()
        except PermissionError:
            self.info_label['fg'] = 'red'
            self.info.set('无法关闭程序：临时文件被占用！\n请关闭程序自动打开的所有word文件后重试！')

    def fuc(self, l):
        self.pid_e.delete(0, 'end')
        for i in l:
            self.pid_e.insert("end", i.decode("gbk") + '\n')


if __name__ == '__main__':
    app = MainWindow()
    app.mainloop()
